package com.ruoyi.system.utils;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import javax.servlet.http.HttpServletRequest;
import com.ruoyi.system.domain.customer.CustomerLogin;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.ip.AddressUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

/**
 * token验证处理
 *
 * @author ruoyi
 */
@Component
public class TokenUtils
{
    private static final String HEADER = "token";

    private static final String secret = "01234567899876543210";

    // 令牌有效期（默认30分钟）
    @Value("${token.expireTime}")
    private  int expireTime;

    protected static final long MILLIS_SECOND = 1000;

    protected static final long MILLIS_MINUTE = 60 * MILLIS_SECOND;

    private static final Long MILLIS_MINUTE_TEN = 20 * 60 * 1000L;

    @Autowired
    private RedisCache redisCache;

    /**
     * 获取用户身份信息
     *
     * @return 用户信息
     */
    public CustomerLogin getLoginCustomer(HttpServletRequest request)
    {
        // 获取请求携带的令牌
        String token = getToken(request);
        if (StringUtils.isNotEmpty(token))
        {
            Claims claims = parseToken(token);
            // 解析对应的权限以及用户信息
            String uuid = (String) claims.get(Constants.LOGIN_USER_KEY);
            String customerKey = getTokenKey(uuid);
            CustomerLogin customer = redisCache.getCacheObject(customerKey);
            return customer;
        }
        return null;
    }

    /**
     * 设置用户身份信息
     */
    public void setLoginCustomer(CustomerLogin loginCustomer)
    {
        if (StringUtils.isNotNull(loginCustomer) && StringUtils.isNotEmpty(loginCustomer.getToken()))
        {
            refreshToken(loginCustomer);
        }
    }

    /**
     * 删除用户身份信息
     */
    public void delLoginCustomer(String token)
    {
        if (StringUtils.isNotEmpty(token))
        {
            String customerKey = getTokenKey(token);
            redisCache.deleteObject(customerKey);
        }
    }

    /**
     * 创建令牌
     *
     * @param loginCustomer 用户信息
     * @return 令牌
     */
    public String createToken(CustomerLogin loginCustomer)
    {
        String token = IdUtils.fastUUID();
        loginCustomer.setToken(token);
        setUserAgent(loginCustomer);
        refreshToken(loginCustomer);

        Map<String, Object> claims = new HashMap<>();
        claims.put(Constants.LOGIN_USER_KEY, token);
        return createToken(claims);
    }

    /**
     * 验证令牌有效期，相差不足20分钟，自动刷新缓存
     *
     * @param loginCustomer
     * @return 令牌
     */
    public void verifyToken(CustomerLogin loginCustomer)
    {
        long expireTime = loginCustomer.getExpireTime();
        long currentTime = System.currentTimeMillis();
        if (expireTime - currentTime <= MILLIS_MINUTE_TEN)
        {
            refreshToken(loginCustomer);
        }
    }

    /**
     * 刷新令牌有效期
     *
     * @param loginCustomer 登录信息
     */
    public void refreshToken(CustomerLogin loginCustomer)
    {
        loginCustomer.setLoginTime(System.currentTimeMillis());
        loginCustomer.setExpireTime(loginCustomer.getLoginTime() + expireTime * MILLIS_MINUTE);
        // 根据uuid将loginUser缓存
        String userKey = getTokenKey(loginCustomer.getToken());
        redisCache.setCacheObject(userKey, loginCustomer, expireTime, TimeUnit.MINUTES);
    }

    /**
     * 设置用户代理信息
     *
     * @param loginCustomer 登录信息
     */
    public void setUserAgent(CustomerLogin loginCustomer)
    {
        String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
        loginCustomer.setIpaddr(ip);
        loginCustomer.setLoginLocation(AddressUtils.getRealAddressByIP(ip));
    }

    /**
     * 从数据声明生成令牌
     *
     * @param claims 数据声明
     * @return 令牌
     */
    private String createToken(Map<String, Object> claims)
    {
        String token = Jwts.builder()
                .setClaims(claims)
                .signWith(SignatureAlgorithm.HS512, secret).compact();
        return token;
    }

    /**
     * 从令牌中获取数据声明
     *
     * @param token 令牌
     * @return 数据声明
     */
    private Claims parseToken(String token)
    {
        return Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJws(token)
                .getBody();
    }

    /**
     * 从令牌中获取用户名
     *
     * @param token 令牌
     * @return 用户名
     */
    public String getCustomerNameFromToken(String token)
    {
        Claims claims = parseToken(token);
        return claims.getSubject();
    }
    /**
     * 获取请求token
     *
     * @param request
     * @return token
     */
    private String getToken(HttpServletRequest request)
    {
        String token = request.getHeader(HEADER);
        if (StringUtils.isNotEmpty(token) && token.startsWith(Constants.TOKEN_PREFIX))
        {
            token = token.replace(Constants.TOKEN_PREFIX, "");
        }
        return token;
    }

    private String getTokenKey(String uuid)
    {
        return Constants.LOGIN_TOKEN_KEY + uuid;
    }
}
